<template>
  <div>
    <el-dialog
      v-toggle-full
      class="base-dialog"
      title="选择检测项目"
      :custom-class="'panna-dialog_big'"
      :visible.sync="dialogVisible"
      :append-to-body="true"
      :before-close="handleClose"
    >
      <p slot="title">选择检测项目</p>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="检测项目" name="first"></el-tab-pane>
        <el-tab-pane label="项目打包" name="second"></el-tab-pane>
      </el-tabs>
      <div style="width: 100%">
        <el-row>
          <el-col style="width: 20%">
            <el-input v-model="filterText" placeholder="树节点查询"></el-input>
          </el-col>
          <el-col style="width: 80%">
            <el-input
              v-model="detectionItemName"
              style="width: 50%"
              placeholder="检测项目查询"
            ></el-input>
            <el-select
              v-model="deteciontItemfilter.scopeAccreditation"
              style="width: 50%"
              placeholder="请选择能力范围"
              @change="getDetectionItemList"
            >
              <el-option
                v-for="item in scopeAccreditationOptions"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-col>
        </el-row>
      </div>
      <div style="float: left; width: 20%; height: 600">
        <el-scrollbar style="width: 95%; height: 600px" class="sampleScrollbar">
          <div class="material-search-tree">
            <el-tree
              ref="tree"
              :filter-node-method="filterNode"
              class="sampleTree"
              :data="treeData"
              :props="defaultProps"
              @node-click="handleNodeClick"
            >
              <span
                slot-scope="{ node }"
                :title="node.label"
                class="el-tree-node__label node-label"
              >
                {{ node.label }}
              </span>
            </el-tree>
          </div>
        </el-scrollbar>
      </div>
      <div style="float: right; width: 80%" class="material-search-container">
        <span>请选择检测项目</span>
        <div class="material-content">
          <el-table
            v-if="show"
            ref="notChooseTableData"
            :data="notChooseTableData"
            border
            height="250"
            @selection-change="NotChooseSelectionChange"
          >
            <el-table-column
              type="selection"
              width="55"
              :selectable="selectEnable"
            />
            <el-table-column prop="detectionItemName" label="项目名称" />
            <el-table-column prop="methodStandard" label="标准方法" />
            <el-table-column prop="scopeAccreditationName" label="能力范围" />
          </el-table>
          <!-- 分页 -->
          <BasePagination
            :total="pageInfo.total"
            :current-page="pageInfo.pageIndex"
            @changePage="changePage"
            @sizeChange="sizeChange"
          />
        </div>
      </div>

      <div style="text-align: center">
        <el-button
          type="primary"
          icon="el-icon-bottom"
          circle
          @click="choiceDetection"
        ></el-button>
        <el-button
          type="primary"
          icon="el-icon-top"
          circle
          @click="cancelChoiceDetection"
        ></el-button>
      </div>
      <div style="float: right; width: 80%" class="material-search-container">
        <span>已选检测项目</span>
        <div class="material-content">
          <el-table
            v-if="show"
            :data="selectedTableData"
            border
            height="250"
            @selection-change="SelectedSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="sampleCategoryName" label="样品名称" />
            <el-table-column prop="detectionItemName" label="项目名称" />
            <el-table-column prop="methodStandard" label="标准方法" />
          </el-table>
        </div>
      </div>

      <span slot="footer" class="base-dialog-footer">
        <el-button type="primary" @click="confirmDetectionItem()"
          >确 定</el-button
        >
        <el-button
          v-if="generateButtonState"
          type="primary"
          style="width: 83px"
          @click="generateAccessory()"
          >生成 附件</el-button
        >
        <el-button @click="handleClose">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  GetSampleTree,
  GetDetectionItem,
  GetListNoPage,
  GetPackDetectionItemData,
  getDictList,
  SelectSampleCategoryParentIdList,
} from "./index.js";
export default {
  name: "ChoiceDetectionItemDialog",
  props: {
    // 是否需要相同的样品类别,默认保存相同的样品类别项目
    sameSampleCategory: {
      type: Boolean,
      default: true,
    },
    editState: {
      type: Boolean,
      default: false,
    },
    value: {
      type: Boolean,
      default: false,
    },
    generateButtonState: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      show: true,
      scopeAccreditationOptions: [],
      scopeAccreditation: "",
      activeName: "first",
      deleteFileIdList: [],
      dialogVisible: false,
      filterText: "",
      detectionItemName: "",
      // 点击编辑的时候传回附件ID
      entrustFileId: 0,
      treeData: [],
      defaultProps: {
        children: "children",
        label: "sampleCategoryName",
      },
      // 流水号
      serialNumber: 1,
      sampleFilterForm: {},
      // 未选择的检测项目表数据
      notChooseTableData: [],
      // 未选择的检测项目表数据复选框选中数据
      notChooseTableDatas: [],
      // 选中的检测项目表数据
      selectedTableData: [],
      // 选中的检测项目表数据复选框选中数据
      selectedTableDatas: [],
      // 记录样品信息
      choiceSampleMaggess: {},
      // 检测项目查询条件
      deteciontItemfilter: {
        sysBusinessSampleCategoryId: 0,
        detectionItemName: "",
        scopeAccreditation: "0",
        id: 0,
      },
      pageInfo: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
      // 返回数据
      sampleDeteciontItemData: [],
    };
  },
  watch: {
    value: function() {
      this.dialogVisible = this.value;
      if (this.value) {
        this.init();
      }
    },
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    detectionItemName(val) {
      this.pageInfo.pageIndex = 1;
      if (val !== null && val !== "") {
        this.deteciontItemfilter.detectionItemName = val;
        this.getDetectionItemList();
      }
    },
    activeName(newVal, newOld) {
      if (newVal === "first") {
        this.defaultProps.label = "sampleCategoryName";
      } else if (newVal === "second") {
        this.defaultProps.label = "packName";
      }
    },
  },
  methods: {
    // 选择页签
    handleClick() {
      this.notChooseTableData = [];
      this.init();
    },
    // 确定检测项目
    confirmDetectionItem() {
      this.jointDetectionData();
      this.jointDetectionItemName();
      this.confirm(1);
    },
    // 拼接检测方法和判定标准
    jointDetectionData() {
      for (let i = 0; i < this.sampleDeteciontItemData.length; i++) {
        // 检测方法
        var detectionMethod = "";
        // 判定标准
        var criterion = "";
        for (
          let o = 0;
          o < this.sampleDeteciontItemData[i].detectionItemData.length;
          o++
        ) {
          // 检测方法
          if (
            this.sampleDeteciontItemData[i].detectionItemData[o]
              .methodStandard !== undefined &&
            this.sampleDeteciontItemData[i].detectionItemData[o]
              .methodStandard !== null
          ) {
            detectionMethod +=
              this.sampleDeteciontItemData[i].detectionItemData[o]
                .methodStandard + ",";
          }
          // 判定标准
          if (
            this.sampleDeteciontItemData[i].detectionItemData[o]
              .productStandardName !== undefined &&
            this.sampleDeteciontItemData[i].detectionItemData[o]
              .productStandardName !== null
          ) {
            criterion +=
              this.sampleDeteciontItemData[i].detectionItemData[o]
                .productStandardName + ",";
          }
        }
        // 检测方法
        if (detectionMethod !== null && detectionMethod !== "") {
          this.sampleDeteciontItemData[i].detectionMethod =
            detectionMethod.substring(0, detectionMethod.length - 1);
        }
        // 判定标准
        if (criterion !== null && criterion !== "") {
          this.sampleDeteciontItemData[i].criterion = criterion.substring(
            0,
            criterion.length - 1
          );
        }
      }
    },
    // 拼接检测项目名称
    jointDetectionItemName() {
      for (let i = 0; i < this.sampleDeteciontItemData.length; i++) {
        this.sampleDeteciontItemData[i].generateFileState = 1;
        var detectionItemName = "";
        for (
          let o = 0;
          o < this.sampleDeteciontItemData[i].detectionItemData.length;
          o++
        ) {
          // 检测项目
          if (
            this.sampleDeteciontItemData[i].detectionItemData[o]
              .detectionItemName !== undefined &&
            this.sampleDeteciontItemData[i].detectionItemData[o]
              .detectionItemName !== null
          ) {
            detectionItemName +=
              this.sampleDeteciontItemData[i].detectionItemData[o]
                .detectionItemName + ",";
          }
        }
        // 检测项目
        if (detectionItemName !== null && detectionItemName !== "") {
          this.sampleDeteciontItemData[i].detectionItemName =
            detectionItemName.substring(0, detectionItemName.length - 1);
        }
      }
    },
    // 生成附件
    generateAccessory() {
      var data = {
        generateAccessoryDtos: [],
        fileName: "",
        entrustFileId: 0,
      };
      data.entrustFileId = this.entrustFileId;
      data.fileName = "附件" + String(this.serialNumber);
      this.jointDetectionData();
      for (let o = 0; o < this.sampleDeteciontItemData.length; o++) {
        for (
          let i = 0;
          i < this.sampleDeteciontItemData[o].detectionItemData.length;
          i++
        ) {
          data.generateAccessoryDtos.push(
            this.sampleDeteciontItemData[o].detectionItemData[i]
          );
        }
      }
      for (let i = 0; i < this.sampleDeteciontItemData.length; i++) {
        this.sampleDeteciontItemData[i].detectionItemName = data.fileName;
        this.sampleDeteciontItemData[i].generateFileState = 2;
      }
      this.confirm(2, data);
    },
    // 取消选择的检测项目
    cancelChoiceDetection() {
      // 判断当页是否又这个数据有就取消选中
      // 删除选中的数据
      for (let i = this.selectedTableData.length - 1; i >= 0; i--) {
        for (let o = 0; o < this.selectedTableDatas.length; o++) {
          if (
            this.selectedTableDatas[o].detectionItemId ===
            this.selectedTableData[i].detectionItemId
          ) {
            this.selectedTableData.splice(i, 1);
            break;
          }
        }
      }
      // selectedTableData选择的表格数据
      // selectedTableDatas是删除的数据

      for (let o = this.sampleDeteciontItemData.length - 1; o >= 0; o--) {
        if (
          this.sampleDeteciontItemData[o].detectionItemData !== null &&
          this.sampleDeteciontItemData[o].detectionItemData.length !== 0
        ) {
          for (
            let p =
              this.sampleDeteciontItemData[o].detectionItemData.length - 1;
            p >= 0;
            p--
          ) {
            for (let t = 0; t < this.selectedTableDatas.length; t++) {
              if (
                this.sampleDeteciontItemData[o].detectionItemData[p]
                  .detectionItemId ===
                this.selectedTableDatas[t].detectionItemId
              ) {
                this.sampleDeteciontItemData[o].detectionItemData.splice(p, 1);
                break;
              }
            }
          }
          if (this.sampleDeteciontItemData[o].detectionItemData.length === 0) {
            this.sampleDeteciontItemData.splice(o, 1);
          }
        }
      }
      // 重新查询检测项目
      if (this.notChooseTableData.length > 0) {
        this.getDetectionItemList();
      }
    },
    // 选择检测项目
    choiceDetection() {
      var detectionItemData = [];
      // 判断是否选择过相同的样品类别和检测项目
      for (let o = this.notChooseTableDatas.length - 1; o >= 0; o--) {
        for (let i = this.selectedTableData.length - 1; i >= 0; i--) {
          // 样品类别页签判断是否有相等的检测项目
          if (this.activeName === "first") {
            if (
              this.selectedTableData[i].sysBusinessSampleCategoryId ===
              this.choiceSampleMaggess.id
            ) {
              // 判断检测项目相同
              if (
                this.selectedTableData[i].detectionItemId ===
                  this.notChooseTableDatas[o].id ||
                this.selectedTableData[i].id === this.notChooseTableDatas[o].id
              ) {
                this.notChooseTableDatas.splice(o, 1);
                break;
              }
            }
          } else if (this.activeName === "second") {
            // 检测项目打包判断是否有相等检测项目
            if (
              this.selectedTableData[i].sysBusinessSampleCategoryId ===
              this.notChooseTableDatas[o].sampleCategory.id
            ) {
              if (
                this.selectedTableData[i].detectionItemId ===
                  this.notChooseTableDatas[o].id ||
                this.selectedTableData[i].id === this.notChooseTableDatas[o].id
              ) {
                this.notChooseTableDatas.splice(o, 1);
                break;
              }
            }
          }
        }
      }
      // 将选择保存到detectionItemData和selectedTableData
      for (let i = 0; i < this.notChooseTableDatas.length; i++) {
        // 样品类别的页签
        if (this.activeName === "first") {
          this.notChooseTableDatas[i].sysBusinessSampleCategoryId =
            this.choiceSampleMaggess.id;
          this.notChooseTableDatas[i].sampleCategoryName =
            this.choiceSampleMaggess.sampleCategoryName;
        } else if (this.activeName === "second") {
          this.notChooseTableDatas[i].sysBusinessSampleCategoryId =
            this.notChooseTableDatas[i].sampleCategory.id;
          this.notChooseTableDatas[i].sampleCategoryName =
            this.notChooseTableDatas[i].sampleCategory.sampleCategoryName;
        }
        this.notChooseTableDatas[i].detectionItemId =
          this.notChooseTableDatas[i].id;
        this.selectedTableData.push(this.notChooseTableDatas[i]);
        detectionItemData.push(this.notChooseTableDatas[i]);
      }
      for (let i = 0; i < detectionItemData.length; i++) {
        var state = 0;
        for (let o = 0; o < this.sampleDeteciontItemData.length; o++) {
          if (
            detectionItemData[i].sysBusinessSampleCategoryId ===
            this.sampleDeteciontItemData[o].sysBusinessSampleCategoryId
          ) {
            state = 1;
            this.sampleDeteciontItemData[o].detectionItemData.push(
              detectionItemData[i]
            );
          }
        }
        if (state === 0) {
          // 没有就加入新对象
          this.sampleDeteciontItemData.push({
            sysBusinessSampleCategoryId:
              detectionItemData[i].sysBusinessSampleCategoryId,
            sampleTypeName: detectionItemData[i].sampleCategoryName,
            detectionItemName: "",
            detectionItemId: "",
            detectionMethod: "",
            sampleNum: "",
            criterion: "",
            detectionItemData: [],
          });
          this.sampleDeteciontItemData[
            this.sampleDeteciontItemData.length - 1
          ].detectionItemData.push(detectionItemData[i]);
        }
      }

      for (var i = 0; i < this.notChooseTableData.length; i++) {
        for (var j = 0; j < this.selectedTableData.length; j++) {
          if (
            this.selectedTableData[j].detectionItemId ===
            this.notChooseTableData[i].detectionItemId
          ) {
            this.notChooseTableData[i].selectEnable = false;
          }
        }
      }
    },
    // 确定
    confirm(generateFileState, data) {
      // const map = new Map();
      // var sampleCount = this.sampleDeteciontItemData.filter(
      //   (key) =>
      //     !map.has(key.sysBusinessSampleCategoryId) &&
      //     map.set(key.sysBusinessSampleCategoryId, 1)
      // );
      // if (sampleCount.length > 1) {
      //   this.$message.error("请选择同一种一级样品类别下的检测项目");
      //   return false;
      // }
      var sampleCategoryIdList = [];
      for (let i = 0; i < this.sampleDeteciontItemData.length; i++) {
        sampleCategoryIdList.push(
          this.sampleDeteciontItemData[i].sysBusinessSampleCategoryId
        );
      }
      if (
        this.sampleDeteciontItemData === null ||
        this.sampleDeteciontItemData.length === 0
      ) {
        this.$emit(
          "DetectionItemClose",
          this.sampleDeteciontItemData,
          generateFileState,
          data
        );
        this.handleClose();
        return false;
      }
      SelectSampleCategoryParentIdList(sampleCategoryIdList).then((res) => {
        if (res.data !== null && res.data.length !== 0) {
          sampleCategoryIdList = [...new Set(res.data)];

          if (this.sameSampleCategory) {
            if (sampleCategoryIdList.length !== 1) {
              this.$message.error("请选择同一种一级样品类别下的检测项目");
              return false;
            }
          }
          if (!this.editState) {
            this.$emit(
              "DetectionItemClose",
              this.sampleDeteciontItemData,
              generateFileState,
              data
            );
            this.handleClose();
          }
        } else {
          this.$message.warning("类别没有顶级数据,请检查!");
          return false;
        }
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      var treeData = [];
      if (this.activeName === "first") {
        treeData = data.label.indexOf(value) !== -1;
      } else if (this.activeName === "second") {
        treeData = data.packName.indexOf(value) !== -1;
      }
      return treeData;
    },
    // 点击节点触发事件
    handleNodeClick(data) {
      this.pageInfo.pageIndex = 1;
      this.pageInfo.pageSize = 10;
      this.pageInfo.total = 0;

      // 样品类别页签直接存入样品类别数据到choiceSampleMaggess
      if (this.activeName === "first") {
        this.choiceSampleMaggess = data;
        this.deteciontItemfilter.sysBusinessSampleCategoryId = data.id;
      } else if (this.activeName === "second") {
        this.deteciontItemfilter.id = data.id;
      }

      this.getDetectionItemList();
    },
    // 查询检测项目方法
    getDetectionItemList() {
      if (this.activeName === "first") {
        GetDetectionItem({
          ...this.deteciontItemfilter,
          ...this.pageInfo,
        }).then((res) => {
          this.notChooseTableData = res.data.dataList ? res.data.dataList : [];
          this.cancelSelectionPitchOn();
          this.pageInfo.total = res.data.total;
        });
      } else if (this.activeName === "second") {
        GetPackDetectionItemData({
          ...this.deteciontItemfilter,
          ...this.pageInfo,
        }).then((res) => {
          this.notChooseTableData = res.data.dataList ? res.data.dataList : [];
          this.cancelSelectionPitchOn();
          this.pageInfo.total = res.data.total;
        });
      }
    },
    selectEnable(row, rowIndex) {
      if (row.selectEnable === false) {
        return false;
      } else {
        return true; // 不禁用
      }
    },
    // 复选框选中
    cancelSelectionPitchOn() {
      // 判断是否又选择过的数据
      for (let i = 0; i < this.notChooseTableData.length; i++) {
        for (let o = 0; o < this.selectedTableData.length; o++) {
          if (
            this.selectedTableData[o].id === this.notChooseTableData[i].id ||
            this.selectedTableData[o].detectionItemId ===
              this.notChooseTableData[i].id
          ) {
            this.notChooseTableData[i].selectEnable = false;

            this.$nextTick(function() {
              this.$refs.notChooseTableData.toggleRowSelection(
                this.notChooseTableData[i],
                true
              );
            });
          }
        }
      }
    },
    sizeChange(val) {
      this.pageInfo.pageIndex = 1;
      this.pageInfo.pageSize = val;
      this.getDetectionItemList();
    },
    // 切换页码
    changePage(page) {
      this.pageInfo.pageIndex = page;
      this.getDetectionItemList();
    },
    // 初始化
    init() {
      // 选择检测项目页签查询样品类别
      // 认证认可范围
      getDictList({ dictCode: "ScopeAccreditation" }).then((res) => {
        res.data.push({
          value: "0",
          id: "0",
          name: "请选择",
        });
        this.scopeAccreditationOptions = res.data;
      });
      if (this.activeName === "first") {
        GetSampleTree(this.sampleFilterForm).then((res) => {
          this.treeData = res.data;
        });
      } else {
        // 查询项目打包
        GetListNoPage().then((res) => {
          this.treeData = res.data;
        });
      }
    },
    // 已选择复选框
    SelectedSelectionChange(val) {
      this.selectedTableDatas = val;
    },
    // 未选择复选框
    NotChooseSelectionChange(val) {
      this.notChooseTableDatas = val;
    },
    // 关闭弹框
    handleClose() {
      this.pageInfo.pageIndex = 1;
      this.pageInfo.pageSize = 1;
      this.pageInfo.total = 0;
      this.deteciontItemfilter = {
        sysBusinessSampleCategoryId: 0,
        detectionItemName: "",
      };
      this.activeName = "first";
      this.filterText = "";
      this.detectionItemName = "";
      this.entrustFileId = 0;
      this.sampleFilterForm = {};
      this.choiceSampleMaggess = {};
      this.selectedTableData = [];
      this.selectedTableDatas = [];
      this.notChooseTableData = [];
      this.notChooseTableDatas = [];
      this.sampleDeteciontItemData = [];
      this.$emit("update:editState", false);
      this.$emit("input", false);
    },
  },
};
</script>

<style lang="scss" scoped>
.node-label {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.sampleTree.el-tree {
  display: inline-block;
  min-width: 90%;
}
</style>
